package com.example.serverlet;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/template")
public class NewsTemplate extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //实例化模板容器
        Configuration configuration = new Configuration();
        //设置加载模板的上下文,以及模板所在路径位置
        configuration.setServletContextForTemplateLoading(getServletContext(),"/template");
        //设置模板的编码格式
        configuration.setDefaultEncoding("UTF-8");
        //加载模板文件,获取具体模板对象
        Template template = configuration.getTemplate("news.ftl");
        //设置数据模型
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("title","1");
        map.put("source","1");
        map.put("pubtime","1");
        map.put("content","1");
        //获取根目录
        String filePath = req.getServletContext().getRealPath("/");
        //设置html的存放路径 (创建一个File实例)
        File file = new File(filePath + "/html");
        //判断文件是否存在 不存在新建
        if (!file.exists()){
            file.mkdir();
        }

        //设置生成的文件名
        String fileName = System.currentTimeMillis() + ".html";
        //创建一个File实例
        File file1 = new File(file,fileName);
        //获取文件输出流
        FileWriter fileWriter = new FileWriter(file1);
        //生成html
        try {
            template.process(map,fileWriter);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }
}
